<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增报表</span>
        <el-button style="float: right" size="mini" @click="goBack">
          <i class="el-icon-back"></i> 返回
        </el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="报表编码" prop="reportCode">
          <el-input v-model="form.reportCode" placeholder="请输入报表编码" style="width: 400px" />
        </el-form-item>
        <el-form-item label="报表名称" prop="reportName">
          <el-input v-model="form.reportName" placeholder="请输入报表名称" style="width: 400px" />
        </el-form-item>
        <el-form-item label="报表类型" prop="reportType">
          <el-select v-model="form.reportType" placeholder="请选择报表类型" style="width: 400px">
            <el-option
              v-for="dict in dict.type.report_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据源" prop="dataSource">
          <el-select v-model="form.dataSource" placeholder="请选择数据源" style="width: 400px">
            <el-option
              v-for="item in datasourceOptions"
              :key="item.dsId"
              :label="item.dsName"
              :value="item.dsId.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryIds">
          <el-select v-model="form.categoryIds" multiple placeholder="请选择报表分类" style="width: 400px">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.categoryId" 
              :label="item.categoryName" 
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionCode">
          <el-input v-model="form.permissionCode" placeholder="请输入权限标识" style="width: 400px" />
        </el-form-item>
        <el-form-item label="状态" prop="reportStatus">
          <el-radio-group v-model="form.reportStatus">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入报表说明"
            maxlength="500"
            show-word-limit
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="resetForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addReport } from "@/api/report/report";
import { listDatasource } from "@/api/report/datasource";
import { getCategoryTree, relateCategory } from "@/api/report/category";

export default {
  name: "AddReport",
  dicts: ['report_type', 'common_status'],
  data() {
    return {
      // 表单参数
      form: {
        reportCode: "",
        reportName: "",
        reportType: "0",
        dataSource: "",
        reportStatus: "0",
        permissionCode: "",
        remark: "",
        categoryIds: []
      },
      // 表单校验
      rules: {
        reportCode: [
          { required: true, message: "报表编码不能为空", trigger: "blur" },
          { min: 2, max: 64, message: '报表编码长度必须在2到64个字符之间', trigger: 'blur' }
        ],
        reportName: [
          { required: true, message: "报表名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '报表名称长度必须在2到100个字符之间', trigger: 'blur' }
        ],
        reportType: [
          { required: true, message: "报表类型不能为空", trigger: "change" }
        ],
        dataSource: [
          { required: true, message: "数据源不能为空", trigger: "change" }
        ]
      },
      // 数据源选项
      datasourceOptions: [],
      // 分类选项
      categoryOptions: []
    };
  },
  created() {
    this.getDatasources();
    this.getCategories();
  },
  methods: {
    // 获取数据源列表
    getDatasources() {
      listDatasource({ pageSize: 100 }).then(response => {
        this.datasourceOptions = response.rows || [];
      });
    },
    // 获取分类列表
    getCategories() {
      getCategoryTree().then(response => {
        this.transformCategoryData(response.data);
      });
    },
    // 转换分类数据为平铺结构
    transformCategoryData(data, parentPath = '') {
      if (!data) return;
      
      data.forEach(item => {
        const path = parentPath ? `${parentPath} / ${item.categoryName}` : item.categoryName;
        
        // 添加到分类列表
        this.categoryOptions.push({
          categoryId: item.categoryId,
          categoryName: path
        });
        
        // 递归处理子分类
        if (item.children && item.children.length > 0) {
          this.transformCategoryData(item.children, path);
        }
      });
    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 先创建报表
          const formData = { ...this.form };
          delete formData.categoryIds; // 移除分类字段，通过关联API单独处理
          
          addReport(formData).then(response => {
            // 获取新创建的报表ID
            const reportId = response.data;
            
            // 如果选择了分类，关联报表与分类
            if (this.form.categoryIds && this.form.categoryIds.length > 0) {
              relateCategory({
                reportId: reportId,
                categoryIds: this.form.categoryIds
              }).then(() => {
                this.$modal.msgSuccess("新增成功");
                this.goBack();
              }).catch(() => {
                this.$modal.msgSuccess("报表创建成功，但分类关联失败");
                this.goBack();
              });
            } else {
              this.$modal.msgSuccess("新增成功");
              this.goBack();
            }
          });
        }
      });
    },
    // 表单重置
    resetForm() {
      this.form = {
        reportCode: "",
        reportName: "",
        reportType: "0",
        dataSource: "",
        reportStatus: "0",
        permissionCode: "",
        remark: "",
        categoryIds: []
      };
      this.$refs["form"] && this.$refs["form"].resetFields();
    },
    // 返回
    goBack() {
      this.$router.push({ path: "/report/list" });
    }
  }
};
</script>

<style scoped>
.preview-container {
  min-height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}
.empty-preview {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}
</style> 